package me.leon.ade

import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

abstract class AbsBindingActivity<VB : ViewBinding> : AppCompatActivity() {

    val binding: VB by lazy {
        javaClass
            .genericSuperclass
            .safeAs<ParameterizedType>()
            ?.actualTypeArguments
            ?.get(0)
            .safeAs<Class<VB>>()
            ?.getMethod("inflate", LayoutInflater::class.java)
            ?.invoke(null, layoutInflater)
            .safeAs<VB>()
            ?: throw IllegalAccessException("not ParameterizedType")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.init()
    }

    abstract fun VB.init()
}

fun <T> Any?.safeAs() = this as? T
